'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import  SystemTray from './platform/electron/SystemTray'
import  WinEventListener from './platform/electron/WinEventListener'
const isDevelopment = process.env.NODE_ENV !== 'production'
let win = null;
let appTray = null;

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  appTray = SystemTray(app,win);
  WinEventListener(app,win);
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    exitApp()
  }
})
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
app.on('ready', async () => {
  createWindow()
})
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        exitApp()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      exitApp()
    })
  }
}

function exitApp(){
  appTray.destroy();
  appTray = null;
  app.quit();
  app.quit();
}